package com.konne.nightmare.FastPublicOpinion.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;

import androidx.annotation.Nullable;

import com.konne.nightmare.FastPublicOpinion.R;

/**
 * Create by ws.
 * on Data:2022/2/10  Time:下午 4:54.
 * description: ** .
 */
public class QJSwitch extends androidx.appcompat.widget.AppCompatImageView {
    private boolean checked;
    private OnCheckedChangeListener onCheckedChangeListener;
    private boolean enabled;
    public QJSwitch(Context context) {
        this(context,null);
    }

    public QJSwitch(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public QJSwitch(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.QJSwitch, defStyleAttr, 0);
        checked = a.getBoolean(R.styleable.QJSwitch_qjs_checked, false);
        enabled=a.getBoolean(R.styleable.QJSwitch_qjs_enabled,true);
        a.recycle();
        if(enabled){
            setOnClickListener(clickListener);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        this.enabled = enabled;
        setOnClickListener(enabled?clickListener:null);
        setImage();
    }

    OnClickListener clickListener=new OnClickListener() {
        @Override
        public void onClick(View view) {
            checked=!checked;
            setImage();
            if(onCheckedChangeListener!=null){
                onCheckedChangeListener.onCheckedChanged(QJSwitch.this,checked);
            }
        }
    };
    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
        setImage();
    }

    private void setImage(){
        if(!checked){
            setImageResource(R.mipmap.bg_switch_track_off);
        }else
        setImageResource(enabled?R.mipmap.bg_switch_track_on:R.drawable.bg_switch_track_on_unuse);

    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public interface OnCheckedChangeListener {
        void onCheckedChanged(QJSwitch var1, boolean var2);
    }
}
